package com.masiyi.parse;

import com.masiyi.entity.Configuration;
import com.masiyi.entity.MappedStatement;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * @Author：掉头发的王富贵
 * @Package：com.masiyi.parse
 * @Project：my-mybatis
 * @name：MapperParse
 * @Date：2023/11/9 22:51
 * @Filename：MapperParse
 * 放置单个实体类对应的xml的
 */
public class MapperParse {


    @SneakyThrows
    public void parse(InputStream resourceAsStream, Configuration configuration) {
        //读取输入流的文件信息，里面存储的即是myMybatisConfig.xml里面全部的内容
        Document document = new SAXReader().read(resourceAsStream);
        //获取最上面的节点，即<mapper>
        Element configurationElement = document.getRootElement();

        Map<String, MappedStatement> mappedStatementMap = configuration.getMappedStatementMap();

        String namespace = configurationElement.attributeValue("namespace");
        List<Element> select = configurationElement.elements("select");


        for (Element element : select) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sql = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setStatementId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setSql(sql);
            mappedStatementMap.put(namespace + "." + id, mappedStatement);
        }
    }

}
